<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="是否处理" prop="isDispose">
        <el-select
          v-model="queryParams.isDispose"
          placeholder="请选择是否处理"
          clearable
        >
          <el-option
            v-for="dict in dict.type.is_dispose"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['crm:cost:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="costList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="所属部门"
        width="120"
        align="center"
        prop="deptName"
      />
      <el-table-column label="用户名称" align="center" prop="userName" />
      <el-table-column
        label="总金额"
        width="100"
        align="center"
        prop="grossAmount"
      />
      <el-table-column label="是否处理" align="center" prop="isDispose">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.is_dispose"
            :value="scope.row.isDispose"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="出差事由"
        width="400"
        align="center"
        prop="businessTrip"
      />
      <el-table-column
        label="费用归属"
        align="center"
        prop="applyAscription"
        width="90"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.sys_data_ascription"
            :value="scope.row.applyAscription"
          />
        </template>
      </el-table-column>
      <el-table-column label="所属客户" align="center" prop="customerName" />
      <el-table-column label="所属商机" align="center" prop="orderName" />
      <el-table-column
        label="归属小组"
        width="90"
        align="center"
        prop="groupId"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.crm_group"
            :value="scope.row.applyGroupId"
          />
        </template>
      </el-table-column>

      <el-table-column label="归属个人" align="center" prop="applyUserName" />
      <el-table-column label="归属部门" align="center" prop="applyDeptName" />
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)"
            >选择费用归属</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改费用管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-row>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-col :span="24">
            <el-form-item label="费用归属" prop="applyAscription">
              <el-select
                v-model="form.applyAscription"
                filterable
                placeholder="请选择费用归属"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.sys_data_ascription"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="所属小组"
              prop="applyGroupId"
              v-if="form.applyAscription === '2'"
            >
              <el-select
                v-model="form.applyGroupId"
                filterable
                placeholder="请选择所属小组"
                style="width: 100%"
              >
                <el-option
                  v-for="dict in dict.type.crm_group"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="所属部门"
              prop="applyDeptId"
              v-if="form.applyAscription === '1'"
            >
              <treeselect
                v-model="form.applyDeptId"
                :options="deptOptions"
                :show-count="true"
                placeholder="请选择所属部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              v-if="form.applyAscription === '0'"
              label="负责人"
              prop="applyUserId"
            >
              <el-select
                v-model="form.applyUserId"
                filterable
                placeholder="请选择负责人"
                style="width: 100%"
              >
                <el-option
                  v-for="order in userList"
                  :key="order.userId"
                  :label="order.userName"
                  :value="order.userId"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属客户" prop="customerId">
              <el-select
                v-model="form.customerId"
                placeholder="请选择客户名称"
                style="width: 100%"
                filterable
                @change="getOrderByCustomerIdAndProgress"
              >
                <el-option
                  v-for="customer in customerList"
                  :key="customer.customerId"
                  :label="customer.customerName"
                  :value="customer.customerId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属商机" prop="orderId">
              <el-select
                v-model="form.orderId"
                filterable
                placeholder="请选择商机"
                style="width: 100%"
              >
                <el-option
                  v-for="item in addOrderList"
                  :key="item.orderId"
                  :label="item.orderName"
                  :value="item.orderId"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCost,
  getCost,
  delCost,
  addCost,
  updateCost,
} from "@/api/crm/cost";
import Treeselect from "@riophae/vue-treeselect";
import { deptTreeSelect } from "@/api/system/user";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  components: { Treeselect },
  name: "Cost",
  dicts: ["is_dispose", "sys_data_ascription", "crm_group"],
  props: {
    userList: {
      type: Array,
      default: [],
    },
    customerList: {
      type: Array,
      default: [],
    },
    orderList: {
      type: Array,
      default: [],
    }
  },
  data() {
    return {
      // 部门树选项
      deptOptions: undefined,
      // 部门名称
      deptName: undefined,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 费用管理表格数据
      costList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        orderId: ''
      },
      // 表单校验
      rules: {},
      // orderList: [],
      addOrderList: []
    };
  },
  created() {
    this.getList();
    this.getDeptTree();
    // this.getOrderListAll()
  },
  methods: {
    getOrderByCustomerIdAndProgress() {
      this.addOrderList = this.orderList
      if(this.form.orderId){
        this.form.orderId = undefined
      }

      this.addOrderList = this.orderList.filter(item => item.customerId === this.form.customerId);
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then((response) => {
        this.deptOptions = response.data;
      });
    },
    /** 查询费用管理列表 */
    getList() {
      this.loading = true;
      listCost(this.queryParams).then((response) => {
        this.costList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        deptId: null,
        userId: null,
        grossAmount: null,
        isDispose: null,
        userName: null,
        deptName: null,
        businessTrip: null,
        createTime: null,
        orderId: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加费用管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getCost(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "选择费用归属";
        this.addOrderList = this.orderList.filter(item => item.customerId === this.form.customerId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCost(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCost(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除费用管理编号为"' + ids + '"的数据项？')
        .then(function () {
          return delCost(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "crm/cost/export",
        {
          ...this.queryParams,
        },
        `cost_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
